package com.xinchao.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinchao.constant.BusinessConstant;
import com.xinchao.constant.ModuleConstant;
import com.xinchao.constant.PageConstant;
import com.xinchao.constant.RequestConstant;
import com.xinchao.dao.RoleMapper;
import com.xinchao.exception.ServiceException;
import com.xinchao.model.OperationLog;
import com.xinchao.model.Role;
import com.xinchao.model.User;
import com.xinchao.model.page.PageInfo;
import com.xinchao.model.vo.RoleListVO;
import com.xinchao.model.vo.RoleSelectListVO;
import com.xinchao.service.OperationLogService;
import com.xinchao.service.RoleService;
import com.xinchao.util.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.rmi.ServerException;
import java.util.List;

/**
 * @author dxy
 * @date 2018/6/22 10:48
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private OperationLogService operationLogService;

	/**
	 * 插入角色
	 *
	 * @param role      Role
	 * @param moduleIds 模块IDS
	 * @param request   HttpServletRequest
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void insertRole(Role role, String moduleIds, HttpServletRequest request) throws ServerException {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		role.setSuperAdminRole(BusinessConstant.SUPER_ADMIN_ROLE_NO);
		role.setAddTime(System.currentTimeMillis());
		//保存角色
		roleMapper.insertRole(role);
		Long roleId = role.getRoleId();
		if (roleId == null) {
			throw new ServerException("返回新增角色ID为空");
		}
		if (StringUtils.isNotBlank(moduleIds)) {
			//保存角色模块关系
			insertRoleModule(roleId, moduleIds);
		}
		//记录操作日志
		OperationLog operationLog = new OperationLog();
		operationLog.setOperationContent("保存角色,角色名为: " + role.getRoleName());
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_ROLE);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 修改角色
	 *
	 * @param role      Role
	 * @param moduleIds 模块IDS
	 * @param request   HttpServletRequest
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateRole(Role role, String moduleIds, HttpServletRequest request) throws ServerException {
		//修改角色
		role.setUpdateTime(System.currentTimeMillis());
		roleMapper.updateRoleById(role);
		Long roleId = role.getRoleId();
		//删除角色模块关系
		roleMapper.deleteRoleModuleByRoleId(roleId);
		if (StringUtils.isNotBlank(moduleIds)) {
			//重新添加角色模块关系
			insertRoleModule(roleId, moduleIds);
		}
		//记录操作日志
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		OperationLog operationLog = new OperationLog();
		operationLog.setOperationContent("修改角色,角色名为: " + role.getRoleName());
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_ROLE);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 保存角色模块关系
	 *
	 * @param roleId    角色ID
	 * @param moduleIds 模块IDS
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void insertRoleModule(Long roleId, String moduleIds) throws ServerException {
		if (roleId == null || StringUtils.isBlank(moduleIds)) {
			throw new ServerException("输入参数部分不能为空");
		}
		roleMapper.insertRoleModule(roleId, moduleIds.split(","));
	}

	/**
	 * 根据角色名称获取角色
	 *
	 * @param roleName 角色名称
	 * @return Role(角色)
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public Role getRoleByRoleName(String roleName) {
		return roleMapper.getRoleByRoleName(roleName, BusinessConstant.STATUS_ENABLE);
	}

	/**
	 * 获取角色列表
	 *
	 * @param status   状态
	 * @param roleName 角色名称
	 * @param pageNum  当前页
	 * @param pageSize 条数
	 * @return PageInfo<RoleListVO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public PageInfo<RoleListVO> listRole(Integer status, String roleName, Integer pageNum, Integer pageSize) {
		//设置默认值
		if (pageNum == null) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null) {
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		PageHelper.startPage(pageNum, pageSize);
		Page<RoleListVO> page = roleMapper.listRole(status, roleName);
		//把Page转化为PageInfo
		PageInfo<RoleListVO> pageInfo = new PageInfo<>();
		pageInfo.setPageNum(pageNum);
		pageInfo.setPageSize(pageSize);
		pageInfo.setTotal(page.getTotal());
		pageInfo.setList(page.getResult());
		return pageInfo;
	}

	/**
	 * 获取所有启用的角色
	 *
	 * @return List<RoleSelectListVO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<RoleSelectListVO> listRoleSelect() {
		return roleMapper.listRoleSelect(BusinessConstant.STATUS_ENABLE);
	}

	/**
	 * 获取角色拥有的权限名称
	 *
	 * @param roleId 角色ID
	 * @return List<String>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<String> listModuleNamesByRoleId(Long roleId) throws ServiceException {
		if (roleId == null) {
			throw new ServiceException("输入参数不能为空");
		}
		return roleMapper.listModuleNamesByRoleId(roleId);
	}

	/**
	 * 根据角色Id获取拥有的权限Id
	 *
	 * @param roleId
	 * @return
	 */
	@Override
	public List<String> listModuleIdsByRoleId(Long roleId) throws ServiceException {
		if (roleId == null) {
			throw new ServiceException("输入参数不能为空");
		}
		return roleMapper.listModuleIdsByRoleId(roleId);
	}

	/**
	 * 启用禁用角色
	 * @param roleId  角色ID
	 * @param status  状态
	 * @param request HttpServletRequest
	 * @throws ServerException
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void enableDisableRole(Long roleId, Integer status, HttpServletRequest request) throws ServerException {
		if (roleId == null || status == null) {
			throw new ServerException("输入参数不能为空");
		}
		Role role = roleMapper.getRoleByRoleId(roleId);
		if (role == null) {
			throw new ServerException("角色不存在");
		}
 		roleMapper.enableDisableRole(roleId, status);
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		//记录操作日志
		OperationLog operationLog = new OperationLog();
		if (BusinessConstant.STATUS_ENABLE == status) {
			operationLog.setOperationContent("修改角色,启用角色" + role.getRoleName());
		} else {
			operationLog.setOperationContent("修改角色,禁用角色" + role.getRoleName());
		}
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_ROLE);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}


	/**
	 * 批量启用禁用角色
	 * @param ids 角色id（多个英文逗号隔开）
	 * @param status 状态
	 * @param loginUser 登录用户
	 * @param ip 登录用户的ip
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void batchAbleDisable(String ids, Integer status, User loginUser, String ip) throws ServiceException {
		StringBuilder roleNames = new StringBuilder();
		if(StringUtils.isNotBlank(ids)){
			String[] idArr = ids.split(",");
			if(idArr.length > 0){
				for (String id : idArr) {
					Role role = roleMapper.getRoleByRoleId(Long.parseLong(id));
					if(role == null){
						throw new ServiceException("角色不存在，请联系管理员");
					}
					roleNames.append(",").append(role.getRoleName());
					roleMapper.enableDisableRole(Long.parseLong(id), status);
				}
			}
			if(StringUtils.isNotBlank(roleNames)){
				String content = "";
				if (BusinessConstant.STATUS_ENABLE == status) {
					content = "批量启用角色，启用角色为：" + roleNames.toString().substring(1);
				} else {
					content = "批量禁用角色，禁用角色为：" + roleNames.toString().substring(1);
				}
				operationLogService.saveSuccessOperationLog(content,
						(ModuleConstant.MODULE_USER_PERMISSION+ "-" + ModuleConstant.MODULE_ROLE), loginUser, ip);
			}
		}
	}
}
